package com.seaboxdata.service.impl;

import com.seaboxdata.entity.DataMonitorResult;
import com.seaboxdata.entity.Sms;
import com.seaboxdata.entity.SmsReceiverConfig;
import com.seaboxdata.service.SmsReceiverConfigService;
import com.seaboxdata.service.SmsService;
import com.seaboxdata.util.HttpUtil;
import com.seaboxdata.util.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.utils.StringUtils;
import org.dom4j.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;

/**
 * @author
 * @create 2020-08-21 16:21
 **/
@Service("smsService")
@Slf4j
public class SmsServiceImpl implements SmsService {

    private static final String NO_LATEST_MONITOR_DATA = "没有查到最新的监控数据,请检查监控程序";

    @Value("${sms.interface}")
    private String smsUrl;

    @Value("${sms.down.xmlName}")
    private String xmlName;

    @Value("${sms.userName}")
    private String userName;

    @Value("${sms.password}")
    private String password;

    @Autowired
    private SmsReceiverConfigService smsReceiverConfigService;

    @Override
    public String insertDownSms(List<DataMonitorResult> invalidResults, List<SmsReceiverConfig> receivers) {
        if (CollectionUtils.isEmpty(receivers)) {
            log.error("smsService:there is no effective receiver");
        }
        StringBuilder msgContent = new StringBuilder();

        if (CollectionUtils.isEmpty(invalidResults)) {
            //监控数据没有正常写入
            msgContent.append(NO_LATEST_MONITOR_DATA);

        } else {
            //监控数据有问题
            for (int i = 0; i < invalidResults.size(); i++) {
                DataMonitorResult dataMonitorResult = invalidResults.get(i);

                msgContent.append("表名:")
                        .append(dataMonitorResult.getTableName())
                        .append(",监控时间:")
                        .append(dataMonitorResult.getMonitorDate().toLocaleString())
                        .append(",最新采集时间:")
                        .append(dataMonitorResult.getLastCjsj() == null ? "空" : dataMonitorResult.getLastCjsj().toLocaleString())
                        .append(",数量")
                        .append(dataMonitorResult.getTotalCount());
                if (i != invalidResults.size() - 1) {
                    msgContent.append(".");
                }
            }
        }

        return sendSms(new String(msgContent), receivers);
    }

    @Override
    public String sendSms(String msg, List<SmsReceiverConfig> receivers) {
        if (StringUtils.isEmpty(msg)) {
            log.error("msg is not allowed null");
            return null;
        }

        String phoneNumber = "";
        for (int i = 0; i < receivers.size(); i++) {
            if (i == receivers.size() - 1) {
                phoneNumber = phoneNumber + receivers.get(i).getPhoneNumber();
            } else {
                phoneNumber = phoneNumber + receivers.get(i).getPhoneNumber() + ",";
            }
        }

        Document document = XmlUtil.readXml(xmlName);
        String xml = document.asXML();
        xml = xml.replace("phoneNumber", phoneNumber);
        xml = xml.replace("publicContentMsg", msg);
        xml = xml.replace("contentMsg", "");
        xml = xml.replace("userNameHolder", userName);
        xml = xml.replace("passwordHolder", password);
        return HttpUtil.postXMLWithUrlConn(smsUrl, xml);
    }

    @Override
    public String sendSms(Sms sms) {
        //暂时支持配置文件发送短信,即传入publicContent内容
        List<SmsReceiverConfig> effectiveReceiver = null;
        if (!ObjectUtils.isEmpty(sms)) {
            if (sms.getPublicContent() == null) {
                log.error("publicContent is not allowed null");
                return null;
            }
            effectiveReceiver = smsReceiverConfigService.getEffectiveReceiver(new Date());
            return sendSms(sms.getPublicContent(), effectiveReceiver);
        }
        return null;
    }

}
